// @charset "utf-8";

define(function(require, exports, module) {
	var publicMethod = require('../../public/public'),
		clientApi = require('../../public/clientapi');

	var template = require('../template/template');
	var chartModel = require('../model/chartmodel');
	var live = require('../live/live');
	var intraday = require('../intraday/intraday');
	var StockChart = require('../../public/stockchart');
	var zhuChart = require('../chart/zhuChart');

	var initRobot = {
		init: async function () {
			var self = this;
			$('#chat-input').on({
				'keydown': function (e) {
					e = e || window.event;
					// var isAltKey = e.altKey && e.keyCode == 83;
					if (e.keyCode == 13) {
						e.preventDefault();
						self.checkText();
					}
				},
				'focus':function(e){
					var $this = $(this);
					if($this.val() == '有什么问题可以问我！'){
						$(this).val('');	
					}
					

				},
				'blur':function(e){
					$this = $(this);
					var text = $this.val();
					if(text == ''){
						$this.val('有什么问题可以问我！');
					}
				}
			});
			
			$('#submit-btn').on('click', function () {
				self.checkText();
			});

			$('#chatContent').on('click',function(e){
				var target = $(e.target);
				
				var label = target.closest('li').data('label') || target.data('label') || target.closest('a').data('label') ;
				var href = target.closest('li').data('href') || target.data('href') || target.closest('a').data('href');
				switch(label){
					case 'movements': //dde资金动向
						template.renderWaitAnswer('movements','dde资金动向',href,1);
						break;
					case 'shbo': //主力大单
						template.renderWaitAnswer('shbo','主力大单',href,1);
						break;
					case 'comprehensive':
						template.renderWaitAnswer('comprehensive','综合报价',href,1);
						break;
					case 'tenplate':
						template.renderUserMsg('资金流入前十板块');
						self.requestAnswer('资金流入前十板块');
						break;
					case 'fundflow':
						template.renderWaitAnswer('fundflow','资金流向',href,1);
						break;
					case 'shortterm':
						template.renderWaitAnswer('shortterm','短线狙击',href,1);
						break;
					case 'platemain':
						template.renderWaitAnswer('platemain','板块主力增仓',href,1);
						break;
					case 'platefundflow':
						template.renderWaitAnswer('platefundflow','板块资金流向',href,1);
						break;
					case 'platerotation':
						template.renderWaitAnswer('platerotation','板块轮动',href,1);
						break;
					case 'newslive': //要闻直播 //换一个要闻直播
						template.renderUserMsg('要闻直播');
						//请求7*24小时数据
						self.sendNewslive();
						
						break;	
					case 'famouslook': //名家看盘
						template.renderUserMsg('名家看盘');

						//获取当前的名家看盘信息的page信息，然后判断是否请求数据并渲染
						var page = chartModel['famousLook']['page'];
						live.sendFamouslook(page);

						break;
					case 'famouspeople': //名家看盘人物头像跳转
						clientApi.openUrlWeb(href,4);
						break;	
					case 'zaopanread': //早盘必读
						template.renderUserMsg('早盘必读');
						//TODO:换个接口回复
						template.renderDefaultAnswer('点击打开复盘必读<a href="###" class="blue" data-label="openzaopan" data-href="http://stock.10jqka.com.cn/zaopan/">http://stock.10jqka.com.cn/zaopan/</a>');
						break;
					case 'openzaopan': //打开早盘必读的链接
						clientApi.openUrlWeb(href,4);
						break;	
					case 'prediction'://涨停预测
						template.renderUserMsg('涨停预测');

						self.requestAnswer('涨停预测');

						
						break;
					case 'globalmarket': //全球市场
						template.renderUserMsg('全球市场');
						live.sendGlobalMarket();
						break;
					case 'various': //各路观点
						template.renderUserMsg('各路观点');

						live.sendVarious();
						break;
					case 'solution': //盘中解盘
						template.renderUserMsg('盘中解盘');
						live.sendSolution();
						break;
					case 'calendar': //投资日历
						template.renderWaitAnswer('calendar','投资日历',href,2);
						break;
					case 'kkgzjp': //看看更早的解盘
						template.renderUserMsg('看看更早的解盘');
						live.sendSolution('',3,'更早的解盘');
						break;	
					case 'jskp': //技术看盘
						template.renderUserMsg('技术看盘');
						live.sendSolution('',1,'技术看盘');
						break;	
					case 'gsqx': //股市气象	
						template.renderUserMsg('股市气象');
						live.sendSolution('',1,'股市气象');
						break;
					case 'jpmore'://盘中解盘查看更多
						clientApi.openUrlWeb(href,4);
						break;	
					case 'change':  //换一换标签轮播
						var len = target.siblings().length - 1; // 7
						
						break;						
					case 'zklhxw': //只看利好新闻
						template.renderUserMsg('利好新闻');
						self.requestAnswer('利好新闻');
						break;
					case 'kklkxw': //看看利空新闻
						template.renderUserMsg('利空新闻');
						self.requestAnswer('利空新闻');
						break;
					case 'ckmore': //查看更多预留
						clientApi.openUrlWeb(href,4);
						break;				
					case 'changePeople': //换一批人

						//template.renderFamouslook();
						break;
					case 'morefamous': //查看更多名家观点
						clientApi.openUrlWeb(href,4);
						break;
					case 'livesay': //看看直播间的大V正在说什么
						template.renderUserMsg('看看直播间的大V正在说什么');
						live.sendLiveSay();
						break;
					case 'changeotherlive': //换一批主播
						template.renderUserMsg('换一批');
						live.sendLiveSay();	
						break;
					case 'changelivesay':
						template.renderUserMsg('主播2');
						live.sendLiveSay();	
						break;	
					case 'technical'://技术面大V
						template.renderUserMsg('技术面大V');
						live.sendLiveSay();	
						break;
					case 'steady'://稳健型大V
						template.renderUserMsg('稳健型大V');
						live.sendLiveSay();	
						break;
					case 'liveCircle': //点击主播头像跳转圈子
						clientApi.openUrlWeb(href,4);
						break;	
					case 'createlive'://创建自己的直播室
						clientApi.openUrlWeb(href,4);
						break;
					case 'successwenju'://回测问句成功率
						template.renderWaitAnswer('successwenju','回测报告',href,2);
						break;
					case 'addfree': //加为自选股

						break;	
					case 'amountmuch'://量太多，继续筛选
						template.renderUserMsg('量太多，继续筛选');
						template.renderDefaultAnswer('好的，告诉我精简条件');
						chartModel['ztyc']['isTrigger'] = 1; //表示可以进行筛选
						break;
					case 'dynamicplate'://设为动态板块
						break;	
					case 'newslink': //新闻链接
						clientApi.openUrlWeb(href,4);
						break;	
					case 'jrrd': //盘后【今日热点】
						template.renderWaitAnswer('jrrd','今日热点',href,1);
						break;
					case 'mrfp': //盘后【每日复盘】
						template.renderWaitAnswer('mrfp','每日复盘',href,2);
						break;
					case 'cjzx'://财经资讯

						break;	
					case 'sjzx'://数据中心

						break;	
					case 'wcxg'://问财选股
					
						break;	
					case 'kchart': //行情图
						new StockChart({
							code: chartModel['historyChart']['content'][href],
							content: '#'+href
						});
						break;
					case 'diagram': //总控接口返回图表
						zhuChart.renderChat(href,chartModel['historyChart']['content'][href]);
						break;
					default:
						break;									
				}
			});

			//先取机器人20条历史记录
			self.renderHistoryChat();

			//引入开盘统计
			await intraday.init();
			
			
		},
		renderRemcommed:async function(){ //渲染每个时间点上的推荐轮播
			var self = this;
			template.renderChatTime();
			
			//取得交易时间
			var tradingDay = parseInt(await clientApi.getTradingDay());
			//取得当前服务器时间:20170303
			var time       = parseInt(await clientApi.serverTime());
			//取得服务器时间hour：1045
			var hour = parseInt(await clientApi.serverHour());
			
			//盘前直播
			template.renderDefaultAnswer('大盘小助手来啦~，还没开盘哦，看看我的推荐，挖掘投资机会吧！',2);
			//1表示早盘,0表示盘中
			template.renderLabelScroll(1);

			//盘中直播
			template.renderDefaultAnswer('开盘啦~大盘小助手来直播啦，还可以看看我的推荐，帮您快速做出决策！',2);
			//1表示早盘,0表示盘中
			template.renderLabelScroll(0);

			//盘后引导
			template.renderDefaultAnswer('收盘啦~大盘小助手来帮您复盘，让您更清晰地把握市场脉搏，时刻胸有成竹！',2);
			//1表示早盘,0表示盘中
			template.renderLabelScroll(8);

			//盘后非交易日0点后引导
			template.renderDefaultAnswer('今天休市哦，还来这里复盘的同学是好同学！刷刷资讯，看看数据，选选股票，轻松也是过一天~',2);
			//1表示早盘,0表示盘中
			template.renderLabelScroll(9);


			//当服务器时间大于交易时间，那么表示盘后
			if(time > tradingDay){

			//当服务器时间小于等于交易日,表明可能是盘前或者是盘中
			}else if(time <= tradingDay){
				//早盘引导
				if(hour < 0930 && hour >= 0600 ){
					
					template.renderDefaultAnswer('大盘小助手来啦~，还没开盘哦，看看我的推荐，挖掘投资机会吧！',2);

				//盘中新闻	
				}else if(hour >= 0935 && hour < 1505){

				//盘后引导
				}else if(hour >= 1505){

				}
				
			}
			
			
			
			
		},
		sendNewslive:function(count,page){  //请求7*24小时早盘新闻接口
			var self     = this;

			//这里做一个随机在newsType之间的切换，
			// var type = Math.round(Math.random());
			var type = 0;
			var newsType = chartModel['realTimeNews']['newsType'][type];
			page         = page || chartModel['realTimeNews']['page'][type];
			
			$.support.cors = true;
			var params = {
				newsType: newsType,
				count: count || 3,
				page: page,
				track:'clientlists'
			};
			var url = 'http://comment.10jqka.com.cn/rapi/main.php?method=lists.thsgd';
			publicMethod.ajaxJson({
				type: 'GET',
				url: url,
				data: params,
				callback: function(result) {
					if(result){
						if(result['code'] === 0){
							if(result['data'].length === 0){
								template.renderDefaultAnswer('当前没有最新的新闻哦！');
							}else{
								template.renderNewslive(result['data']);
								chartModel['realTimeNews']['page'][type] ++;
							}
						}else{
							template.renderDefaultAnswer('当前没有最新的新闻哦！');
						}
					}else{
						template.renderDefaultAnswer('网络异常！请检查');
					}
				}
				
			});	
		},
		
		checkText: function () {
			var self = this;
			var trimTxt = $.trim($('#chat-input').val());
			if (trimTxt == $('#chat-input').attr('data-val') || trimTxt === '') {
				return;
			}

			

			//判断系统模块



			self.sendMessage(trimTxt);
		},
		sendMessage: function (qTxt) {
			var self = this;
			qTxt = qTxt || $.trim($('#chat-input').val());
			
			//为1 表示进入筛选提问
			if(chartModel['ztyc']['isTrigger'] === 1){
				chartModel['ztyc']['content'].push(qTxt);
				qTxt = chartModel['ztyc']['content'].join(',');
				
			}else{
				chartModel['ztyc']['content'] = ['涨停预测'];
			}

			template.renderUserMsg(qTxt);


			self.requestAnswer(qTxt);
			// publicMethod.chatScrollTo();
			$('#chat-input').val('');
		},
		requestAnswer: function (qTxt) {
			var self = this;
			$.support.cors = true;
			var params = {
				username: clientApi.userName,
				userid: clientApi.userId,
				question: qTxt
			};
			var url = 'http://sp.10jqka.com.cn/liuyan/message/getroutereply/';
			publicMethod.ajaxJson({
				type: 'POST',
				url: url,
				data: params,
				callback: function(result) {
					if(!result){
						template.renderDefaultAnswer('网络异常！请检查');
					}
					var answer = result.answer;
					if(result.status === 0 && answer.length > 0){
						for(var i = 0, len = answer.length; i < len; i ++){
							self.setRenderType(answer[i]['source'],answer[i],0,qTxt);
							
							if(qTxt == '涨停预测' || chartModel['ztyc']['isTrigger'] === 1){
								template.renderPrediction();

							}
							
						}//for循环结束
					}else if(result.status === -1 && answer.length > 0){
						for(var i = 0, len = answer.length; i < len; i ++){
							//主搜索 目前只会有txt数据的单元格式
							self.setRenderType(answer[i]['source'],answer[i],0,qTxt);
							// switch (answer[i]['source']){
							// 	case 'kefu':
							// 		template.renderRootKefu(answer[i]);
							// 		break;

							// }//switch结束
							
						}//for循环结束
						
					}//if{}else{}结束
					chartModel['ztyc']['isTrigger'] = 0;

					
				} //callback结束

			});
		},
		renderHistoryChat:function(){ //渲染机器人对话历史记录
			
			var self = this;
			$.support.cors = true;
			var params = {
				pagesize: 10,
				userid: clientApi.userId,
				page: 1
			};
			var url = 'http://sp.10jqka.com.cn/liuyan/message/getroutehistory/';
			publicMethod.ajaxJson({
				type: 'GET',
				url: url,
				data: params,
				callback:function(result){
					if(result.errorcode === 0){
						result = result['result'];
						//倒序
						result.reverse();
						for(var i = 0, len = result.length; i < len; i ++){

							//1---渲染用户问问题记录
							template.renderUserMsg(result[i]['content'],1);
							
							if(result[i]['answer'] === false ){

								template.renderDefaultAnswer('',1);
								if(i === len -1){
									template.renderHistoryChat();
								}
								continue;
							}
							var answer = result[i]['answer']['answer'];
							for( var j = 0,len2 = answer.length; j < len2; j ++){
								//2---渲染机器人回复记录
								self.setRenderType(answer[j]['source'],answer[j],1,result[i]['content']);
							}
							
							if(i === len - 1){
								
								template.renderHistoryChat();
							}
						}

					}

					//然后未开盘时出现推荐
					self.renderRemcommed();
					
					//$('#chat-input').val($('#chatContent').html());
				}
			});
		},
		setRenderType:function(source,answer,flag,qtxt){
			switch(source){
				//主搜索 目前只会有txt数据的单元格式
				case 'soniu': 
					template.renderRootText(answer,flag);
					break;
				//目前会有diagram结果集数据和txt结果集数据；	
				case 'zhengu': 
					template.renderRootZhengu(answer,flag,qtxt);
					break;
				case 'iwencai':
					template.renderRootIwencai(answer,flag,qtxt);	
					break;
				case 'kefu':
					template.renderRootKefu(answer,flag);
					break;
			}
		}
	};

	module.exports = initRobot;
});